/**
 * 通用API错误处理模块
 * 提供标准HTTP错误类和状态码，用于API响应
 */

/**
 * API错误基类
 */
class ApiError extends Error {
  /**
   * 创建API错误
   * @param {string} message 错误消息
   * @param {number} statusCode HTTP状态码
   * @param {string} code 错误代码
   * @param {object} data 附加数据
   */
  constructor(message, statusCode = 500, code = 'INTERNAL_SERVER_ERROR', data = {}) {
    super(message || 'Internal Server Error');
    this.name = this.constructor.name;
    this.statusCode = statusCode;
    this.code = code;
    this.data = data;

    // 捕获堆栈跟踪
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, this.constructor);
    }
  }
}

/**
 * 400 Bad Request - 请求参数有误
 */
class BadRequestError extends ApiError {
  constructor(message = '请求参数有误', code = 'BAD_REQUEST', data = {}) {
    super(message, 400, code, data);
  }
}

/**
 * 401 Unauthorized - 未授权
 */
class UnauthorizedError extends ApiError {
  constructor(message = '请先登录', code = 'UNAUTHORIZED', data = {}) {
    super(message, 401, code, data);
  }
}

/**
 * 403 Forbidden - 禁止访问
 */
class ForbiddenError extends ApiError {
  constructor(message = '无权访问', code = 'FORBIDDEN', data = {}) {
    super(message, 403, code, data);
  }
}

/**
 * 404 Not Found - 资源不存在
 */
class NotFoundError extends ApiError {
  constructor(message = '资源不存在', code = 'NOT_FOUND', data = {}) {
    super(message, 404, code, data);
  }
}

/**
 * 409 Conflict - 资源冲突
 */
class ConflictError extends ApiError {
  constructor(message = '资源已存在', code = 'CONFLICT', data = {}) {
    super(message, 409, code, data);
  }
}

/**
 * 422 Unprocessable Entity - 无法处理的实体
 */
class ValidationError extends ApiError {
  constructor(message = '数据验证失败', code = 'VALIDATION_ERROR', data = {}) {
    super(message, 422, code, data);
  }
}

/**
 * 500 Internal Server Error - 服务器内部错误
 */
class InternalServerError extends ApiError {
  constructor(message = '服务器内部错误', code = 'INTERNAL_SERVER_ERROR', data = {}) {
    super(message, 500, code, data);
  }
}

/**
 * 503 Service Unavailable - 服务不可用
 */
class ServiceUnavailableError extends ApiError {
  constructor(message = '服务暂时不可用', code = 'SERVICE_UNAVAILABLE', data = {}) {
    super(message, 503, code, data);
  }
}

// 导出所有错误类
module.exports = {
  ApiError,
  BadRequestError,
  UnauthorizedError,
  ForbiddenError,
  NotFoundError,
  ConflictError,
  ValidationError,
  InternalServerError,
  ServiceUnavailableError
}; 